//
//  ConfigTixianViewController.m
//  customer
//
//  Created by 往返网络 on 17/8/24.
//  Copyright © 2017年 com. All rights reserved.
//

#import "ConfigTixianViewController.h" //提现确认界面
#import "SuccedTixianViewController.h"  //提现成功界面

#define return_tag 1000
#define config_tag 1001
#define yanzheng_tag 1002
#define min_h 80.0/H_BASE*SCREEN_H
#define begin_x 25.0/W_BASE*SCREEN_W
//定义确认提现URL
#define URL_QUEREN [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payGetCashConfig?type=get",BASE_URL]
//定义验证码值URL
#define URL_GETCODE [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payGetCashSend?type=get",BASE_URL]

@interface ConfigTixianViewController ()<UITextFieldDelegate>
//开辟多线程定时器，在后台执行，比NSTimer更自然
@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@property (nonatomic,copy)NSString * sendcode; //点击发送验证码

@end
@implementation ConfigTixianViewController
{
    UITextField * messagetf; //验证码TF
    UIButton * messbtn; //验证码btn


}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    // Do any additional setup after loading the view.
}
- (void)createUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    //设置表头
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    
    //title
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20.0, SCREEN_W, 90.0/H_BASE*SCREEN_H)];
    titlelab.text = @"提现信息确认";
    
    titlelab.textColor = [UIColor whiteColor];
    
    [self.view addSubview:titlelab];
    
    titlelab.textAlignment = NSTextAlignmentCenter;
    
    titlelab.font = [UIFont systemFontOfSize:fontsize];
    
    UILabel * leftlable  = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    leftlable.textAlignment = NSTextAlignmentCenter;
    NSString * endstr = @"\U0000e697";
    NSString * text = [NSString stringWithFormat:@"%@%@",endstr,@"返回"];
    leftlable.attributedText = [self changeLabelWithText2:text andStartplace:endstr andendplae:nil andfontsize:fontsize-2];
    leftlable.textColor = [UIColor whiteColor];
    [self.view addSubview:leftlable];
    
    UIButton * returnbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150.0/W_BASE*SCREEN_W, 150.0/H_BASE*SCREEN_H)];
    [returnbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    returnbtn.tag = return_tag;
    [self.view addSubview:returnbtn];
    
    UIView * backview = [[UIView alloc]initWithFrame:CGRectMake(0, 127.0/H_BASE*SCREEN_H, SCREEN_W, SCREEN_H-127.0/H_BASE*SCREEN_H)];
    backview.backgroundColor = COLORRGBA(239, 239, 239, 1);
    [self.view addSubview:backview];
    
    UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(titleview.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W, min_h)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    
    UILabel * banktitle = [[UILabel alloc]initWithFrame:CGRectMake(begin_x, 0, 160.0/W_BASE*SCREEN_W, min_h)];
    banktitle.text = @"银行卡号";
    banktitle.textColor = COLORRGBA(102, 102, 102, 1);
    banktitle.textAlignment = NSTextAlignmentLeft;
    [view1 addSubview:banktitle];
    banktitle.font = [UIFont systemFontOfSize:fontsize-2];
    
    UILabel * numlabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(banktitle.frame), 0, SCREEN_W - CGRectGetMaxX(banktitle.frame)-25.0/W_BASE*SCREEN_W, min_h)];
    numlabel.textAlignment = NSTextAlignmentRight;
    [view1 addSubview:numlabel];
    NSString * firstring = [self.banknumstring substringToIndex:4];
    NSString * endstring = [self.banknumstring substringFromIndex:_banknumstring.length -4];
    numlabel.text = [NSString stringWithFormat:@"%@ **** **** **** %@",firstring,endstring];
    numlabel.font = [UIFont systemFontOfSize:fontsize-4];
    
    UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view1.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W, min_h)];
    view2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view2];
    
    UILabel * jinelabel = [[UILabel alloc]initWithFrame:CGRectMake(begin_x, 0, 160.0/W_BASE*SCREEN_W, min_h)];
    jinelabel.text = @"提现金额";
    jinelabel.textColor = COLORRGBA(102, 102, 102, 1);
    jinelabel.textAlignment = NSTextAlignmentLeft;
    [view2 addSubview:jinelabel];
    jinelabel.font = [UIFont systemFontOfSize:fontsize-2];
    
    UILabel * jinestr = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(banktitle.frame), 0, SCREEN_W - CGRectGetMaxX(banktitle.frame)-25.0/W_BASE*SCREEN_W, min_h)];
    jinestr.textAlignment = NSTextAlignmentRight;
    [view2 addSubview:jinestr];
    jinestr.text = self.jinestring;
    jinestr.font = [UIFont systemFontOfSize:fontsize-4];

    UIView * view3 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view2.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W, min_h)];
    view3.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view3];
    
    UILabel * phonelab = [[UILabel alloc]initWithFrame:CGRectMake(begin_x, 0, 160.0/W_BASE*SCREEN_W, min_h)];
    phonelab.text = @"手机号";
    phonelab.textColor = COLORRGBA(102, 102, 102, 1);
    phonelab.textAlignment = NSTextAlignmentLeft;
    [view3 addSubview:phonelab];
    phonelab.font = [UIFont systemFontOfSize:fontsize-2];
    
    UILabel * phonestr = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(banktitle.frame), 0, SCREEN_W - CGRectGetMaxX(banktitle.frame)-25.0/W_BASE*SCREEN_W, min_h)];
    phonestr.textAlignment = NSTextAlignmentRight;
    [view3 addSubview:phonestr];
    phonestr.text = self.jinestring;
    phonestr.font = [UIFont systemFontOfSize:fontsize-4];
    NSString * first = [[[NSUserDefaults standardUserDefaults]objectForKey:USERDEFAULTS_PHONE]substringToIndex:3];
    NSString * end = [[[NSUserDefaults standardUserDefaults]objectForKey:USERDEFAULTS_PHONE]substringFromIndex:7];
    phonestr.text = [NSString stringWithFormat:@"%@****%@",first,end];
    
    UIView * view4 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view3.frame)+20.0/H_BASE*SCREEN_H, SCREEN_W,min_h )];
    view4.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view4];
    
    UILabel * yanzhenglab = [[UILabel alloc]initWithFrame:CGRectMake(20.0/W_BASE*SCREEN_W, 0, 300.0/W_BASE*SCREEN_W, min_h)];
    yanzhenglab.textAlignment = NSTextAlignmentLeft;
    yanzhenglab.textColor = COLORRGBA(102, 102, 102, 1);
    yanzhenglab.text = @"验证码";
    yanzhenglab.font = [UIFont systemFontOfSize:fontsize-2];
    [view4 addSubview:yanzhenglab];
    
    messagetf = [[UITextField alloc]initWithFrame:CGRectMake(130.0/W_BASE*SCREEN_W, 0, 150.0/W_BASE*SCREEN_W, min_h)];
    messagetf.font = [UIFont systemFontOfSize:fontsize-2];
    messagetf.delegate = self;
    messagetf.keyboardType = UIKeyboardTypeNumberPad;
    [view4 addSubview:messagetf];
    
    messbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W- 180.0/W_BASE*SCREEN_W, CGRectGetMinY(messagetf.frame)+10.0/H_BASE*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H)];
    messbtn.layer.cornerRadius = 2;
    messbtn.layer.borderColor = [COLORRGBA(255, 102, 102, 1)CGColor];
    messbtn.layer.borderWidth = 1;
    messbtn.clipsToBounds = YES;
    messbtn.backgroundColor = [UIColor whiteColor];
    messbtn.clipsToBounds = YES;
    [messbtn setTitleColor:COLORRGBA(255, 102, 102, 1) forState:UIControlStateNormal];
    messbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize - 5];
    [view4 addSubview:messbtn];
    [messbtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    messbtn.tag = yanzheng_tag;
    [messbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * configbtn = [[UIButton alloc]initWithFrame:CGRectMake(30.0/W_BASE*SCREEN_W, CGRectGetMaxY(view4.frame)+30.0/H_BASE*SCREEN_H, SCREEN_W - 60.0/W_BASE*SCREEN_W, min_h)];
    configbtn.backgroundColor = COLORRGBA(59, 214, 117, 1);
    [self.view addSubview:configbtn];
    [configbtn setTitle:@"确认提现" forState:UIControlStateNormal];
    [configbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [configbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    configbtn.tag = config_tag;

       
}

#pragma mark  -  -  起始地＋发货人名（终止地＋收货人名）格式化 － － －-- - -  -
-(NSMutableAttributedString*)changeLabelWithText2:(NSString*)needText andStartplace:(NSString *)startplace andendplae:(NSString *)endplace andfontsize:(float)fontsize
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:needText];
    NSInteger startlength = startplace.length;
    //起始格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"iconfont" size:fontsize+2] range:NSMakeRange(0,startlength)];
    //    //尾部格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontsize] range:NSMakeRange(startlength , needText.length  - startlength)];
    return attrString;
    
}
- (void)getYanzhengString{
    
    //字符串反转之后，再发送出去 phonenum --- 反转 －－－＊2 －－－ 转化为a-z
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&money=%@",URL_GETCODE,token,self.jinestring];
    NSLog(@"提现验证码 url %@",url);
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"dict %@",dict);
            NSInteger code = [dict[@"code"]integerValue];
            if (code == 0) {
                NSLog(@"code 为0");
                //获取验证码成功 及相应充值参数
               _sendcode = @"1";
                [self loadTimer];
                
            }else{
                
                NSLog(@"get code no");
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
            }
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    
}


- (void)configTixian{
    if (![_sendcode isEqualToString:@"1"]) {
        ALERT(@"提示", @"请获取验证码", self, @"确定", nil);
        return;
    }
    
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    //去除空格
     NSString * accountNo = [self.accountNo stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSString *  accountName = [self.accountName stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSString *  accountBankName = [self.accountBankName stringByReplacingOccurrencesOfString: @" " withString: @""];
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&money=%@&accountNo=%@&accountName=%@&accountBankName=%@&code=%@",URL_QUEREN,token,self.jinestring,accountNo,accountName,accountBankName,messagetf.text];
    NSString * URL  = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"确认提现 url %@",URL);
    [self.manger GET:URL parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject) {
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"dict %@",dict);
            NSInteger code = [dict[@"code"]integerValue];
            if (code == 0) {
                NSLog(@"充值成功");
                SuccedTixianViewController * succtixianvc = [[SuccedTixianViewController alloc]init];
                succtixianvc.jinestring = self.jinestring;
                [self.navigationController pushViewController:succtixianvc animated:YES];
            }else{
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
}

#pragma mark - - - - - - - - - - -  Action - - - - - - - - - - - - -
- (void)enterClick:(UIButton *)btn{
    
    switch (btn.tag) {
        case return_tag:
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case yanzheng_tag:
            //获取验证码
        {
            [self getYanzhengString];
            break;
        }
        case config_tag:
            //确认
        {
            if (messagetf.text.length == 0) {
                ALERT(@"提示", @"验证码格式有误", self, @"确定", nil);
                return;
            }

            [self configTixian];
            break;
        }
    }
}


- (void)loadTimer{
    
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [messbtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [messbtn setTitleColor:COLORRGBA(255, 102, 102, 1) forState:UIControlStateNormal];
                messbtn.layer.cornerRadius = 2;
                messbtn.layer.borderColor = [COLORRGBA(255, 102, 102, 1)CGColor];
                messbtn.layer.borderWidth = 1;
                messbtn.clipsToBounds = YES;
                messbtn.backgroundColor = [UIColor whiteColor];
                messbtn.clipsToBounds = YES;
                
                messbtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果 %2d秒后重新发送
                [messbtn setTitle:[NSString stringWithFormat:@"已发送(%2ds)", seconds] forState:UIControlStateNormal];
                messbtn.layer.borderWidth = 0;
                messbtn.backgroundColor = COLORRGBA(238, 240, 239, 1);
                [messbtn setTitleColor:COLORRGBA(174, 174, 173, 1) forState:UIControlStateNormal];
                
                messbtn.userInteractionEnabled = NO;
            });
            time--;
            
        }
    });
    
    dispatch_resume(_timer);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.view endEditing:YES];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    
}
- (AFHTTPSessionManager*)manger{
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    }
    
    return _manger;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
